package com.kim.authorization.server.config.extend;

import com.kim.oauth.common.model.UserAccount;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Project: kim-security-oauth
 * @PackageName: com.kim.authorization.server.config.extend
 * @FileName: CustomTokenServices.java
 * @Description: The CustomTokenServices is...
 * @Author: kimwu
 * @Time: 2020-12-14 16:55:24
 */
@Slf4j
@Component
public class CustomTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        UserAccount principal = (UserAccount) authentication.getUserAuthentication().getPrincipal();
        if (accessToken instanceof DefaultOAuth2AccessToken) {
            DefaultOAuth2AccessToken token = ((DefaultOAuth2AccessToken) accessToken);
            token.setValue(getNewToken(principal));
            OAuth2RefreshToken refreshToken = token.getRefreshToken();
            if (refreshToken instanceof DefaultOAuth2RefreshToken) {
                token.setRefreshToken(new DefaultOAuth2RefreshToken(getNewToken(principal)));
            }
            Map<String, Object> additionalInformation = new HashMap<String, Object>();
            additionalInformation.put("client_id", authentication.getOAuth2Request().getClientId());
            token.setAdditionalInformation(additionalInformation);
            return token;
        }
        return accessToken;
    }

    private String getNewToken(UserAccount userAccount) {
        return UUID.randomUUID().toString();
    }
}
